package io.gitee.icefairy.total_monitor.task

import cn.hutool.core.io.resource.ResourceUtil
import cn.hutool.db.Db
import cn.hutool.db.Entity
import cn.hutool.log.LogFactory
import io.gitee.icefairy.total_monitor.DbConfig
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.DependsOn
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit
import javax.annotation.PostConstruct

/**
 * AUTHOR:icefairy
 * DATE:2021/12/23 0023 19:36
 **/
@Component
@DependsOn(value = arrayOf("DbConfig"))
open class InitDbTask {
    @Autowired
    lateinit var db: Db

    val log = LogFactory.get()

    @PostConstruct
    fun init() {
        GlobalScope.async {
            log.info("init mymenu")
            TimeUnit.SECONDS.sleep(9)
            val ite=db.find(Entity.create("e_upms_menu").set("code", "itemmgr"))
            if (ite.isEmpty()) {
                val lines = ResourceUtil.getUtf8Reader("import.sql").lines()
                lines.forEach {
                    try {
                        db.execute(it)
                        log.info("execSql:$it")
                    } catch (e: Exception) {
                        log.error(e)
                    }

                }
                log.info("mymenu inited ok")
            } else {
                log.warn("mymenu has already inited")
            }
        }
    }
}